import router from '@/router'
import store from '@/store'

export default {
  inserted(el, binding) {
    const { value } = binding
    if (value) {
      const scope = value
      const hasPermission = getPermission(scope)

      if (!hasPermission) {
        el.parentNode && el.parentNode.removeChild(el)
      }
    } else {
      throw new Error(`请设置按钮scope权限! 例如 v-permission="1"`)
    }
  }
}

export function getPermission(scope) {
  // 超级管理员返回所有用户权限
  if (store.getters.userInfo && ((store.getters.userInfo.utype & 0x01) === 0x01)) return true
  const currentRoute = router.currentRoute
  if (!currentRoute.meta || (!currentRoute.meta.btnScopes)) return true
  const btnScopes = currentRoute.meta.btnScopes
  if (btnScopes.length === 1 && btnScopes[0] === 0) return true
  return btnScopes.some(btnScope => btnScope >> (scope - 1) & 0x01)
}
